package it.uni.bo.monitoring.sla.chain.causality;

import it.uni.bo.monitoring.protocol.unmarshaller.EventInfo;
import it.uni.bo.monitoring.sla.context.AutomataState;
import it.uni.bo.monitoring.sla.context.AutomataTransition;
import it.uni.bo.monitoring.sla.context.ComponentManager;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import static it.uni.bo.monitoring.service.StaticFields.QUERY_SQL_VIOLATION;

public class PatternManager implements ComponentManager{

	private AutomataState cur_st;	
	private SessionFactory factory;
	private Logger l;
	private String description;
	private final static String DESC_VIOLATION="PATTERN VIOLATION DETECTED\n";
	
	public PatternManager(AutomataState init_st, SessionFactory factory) {
		l = Logger.getLogger(this.getClass());
		cur_st = init_st;
		this.factory=factory;
	}

	public void makeTrans(EventInfo ei) {
		AutomataTransition at = this.cur_st.getTransition(ei.getOperationName());
		if(at != null){
			AutomataState as = at.getTarget();
			cur_st=as;
			if ( as.getName().equalsIgnoreCase("Error")) {
				description=DESC_VIOLATION+ " | "+ei.getAppUrl()+ " | "+ei.getNamespace()+ " | "+ei.getOperationName()+" | ";
				l.info(description);
				if(factory!=null){
					Session session=factory.openSession();
					Query query = session.createSQLQuery(QUERY_SQL_VIOLATION);
					query.setString(0, "pattern");
					query.setLong(1, ei.getIdSla());
					query.setBinary(2, ei.getIdE());
					query.setString(3, description);
					l.info("Hibernate: "+QUERY_SQL_VIOLATION+" [ pattern "+ei.getIdSla()+" "+new String(ei.getIdE())+" "+description+" ]");
					query.executeUpdate();
					if ((session!=null) && (session.isOpen())) 
						session.close(); 

				}
			}
		}	
	}

}
